package cn.com.chengmandian.bike.service.impl;

import cn.com.chengmandian.bike.model.EbMemberLife;
import cn.com.chengmandian.bike.mapper.EbMemberLifeMapper;
import cn.com.chengmandian.bike.service.IEbMemberLifeService;
import cn.com.chengmandian.core.common.utils.HttpUtils;
import cn.com.chengmandian.core.web.exceptions.BadResponseException;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 电单车运营-活体检测记录 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2024-06-24
 */
@Slf4j
@Service
public class EbMemberLifeServiceImpl extends ServiceImpl<EbMemberLifeMapper, EbMemberLife> implements IEbMemberLifeService {

    private final static String LIFE_API_POST = "https://jmxgjmhtrz.market.alicloudapi.com";

    @Override
    public EbMemberLife initLifeCheck(AgentInfo agentInfo, Integer businessType, Integer memberId, String mobile, String returnUrl, String colors, String actions, String name, String idCard) {
        Assert.isTrue(StrUtil.isNotBlank(agentInfo.getFaceAppcode()), "缺少人脸识别APP_CODE");

        String path = "/xgjmhtrz/lifecheck/init";
        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + agentInfo.getFaceAppcode());
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("returnUrl", returnUrl);
        bodys.put("colors", colors);
        bodys.put("actions", actions);

        EbMemberLife ebMemberLife = new EbMemberLife();
        ebMemberLife.setMemberId(memberId);
        ebMemberLife.setMemberMobile(mobile);
        ebMemberLife.setName(name);
        ebMemberLife.setIdCard(idCard);
        ebMemberLife.setBusinessType(businessType);

        Integer requestResult = 200;
        String requestMsg = "";
        String intiAuthToken = "";
        try {
            HttpResponse response = HttpUtils.doPost(LIFE_API_POST, path, "POST", headers, querys, bodys);
            int statusCode = response.getStatusLine().getStatusCode();
            requestResult = statusCode;
            if(statusCode != 200) {
                throw new BadResponseException(statusCode + "：人脸识别初始化失败");
            }
            // 解析响应数据
            Map<String, Object> authResponseMap = JSONObject.parseObject(EntityUtils.toString(response.getEntity()), Map.class);
            log.info("活体检测初始化响应:{}", JSONObject.toJSONString(authResponseMap));
            Integer responseCode = MapUtil.getInt(authResponseMap, "code");
            requestResult = responseCode;
            if(!responseCode.equals(Integer.valueOf(200))){
                throw new BadResponseException(MapUtil.getStr(authResponseMap, "msg"));
            }
            requestMsg = MapUtil.getStr(authResponseMap, "msg");
            String userAuthData = MapUtil.getStr(authResponseMap, "data");
            if(StrUtil.isBlank(userAuthData)) {
                throw new BadResponseException("人脸活体识别初始化异常");
            }
            Map<String, Object> responseDataMap = JSONObject.parseObject(userAuthData, Map.class);
            intiAuthToken = MapUtil.getStr(responseDataMap, "token");
            if(StrUtil.isBlank(intiAuthToken)) {
                throw new BadResponseException("life init token is null");
            }
        } catch (Exception e) {
            ebMemberLife.setInitResult(requestResult);
            ebMemberLife.setInitMessage(e.getMessage());
            ebMemberLife.setThirdToken(intiAuthToken);
            this.save(ebMemberLife);
            throw new BadResponseException(e.getMessage());
        }
        ebMemberLife.setInitResult(requestResult);
        ebMemberLife.setInitMessage(requestMsg);
        ebMemberLife.setThirdToken(intiAuthToken);
        this.save(ebMemberLife);
        return ebMemberLife;
    }

    @Override
    public EbMemberLife startLifeCheck(String token, AgentInfo agentInfo) {
        Assert.isTrue(StrUtil.isNotBlank(agentInfo.getFaceAppcode()), "缺少人脸识别APP_CODE");
        EbMemberLife memberLife = this.getByToken(token);
        Assert.isTrue(StrUtil.isNotBlank(memberLife.getThirdToken()), "活体检测异常：缺少TOKEN");

        String path = "/xgjmhtrz/lifecheck/result";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + agentInfo.getFaceAppcode());
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("token", memberLife.getThirdToken());
        log.info("活体检测参数：face-app-code:{}  bodys-{}", agentInfo.getFaceAppcode(), JSONObject.toJSONString(bodys));

        LambdaUpdateWrapper<EbMemberLife> updateWrapper = new LambdaUpdateWrapper<EbMemberLife>();
        updateWrapper.eq(EbMemberLife::getId, memberLife.getId());
        Integer checkResult = 200;
        String checkMessage = "";
        String checkFaceImg = "";
        try {
            HttpResponse response = HttpUtils.doPost(LIFE_API_POST, path, "POST", headers, querys, bodys);
            // 解析响应数据
            Map<String, Object> authResponseMap = JSONObject.parseObject(EntityUtils.toString(response.getEntity()), Map.class);
            log.info("活体检测结果响应:{}", JSONObject.toJSONString(authResponseMap));
            Integer responseCode = MapUtil.getInt(authResponseMap, "code");
            checkResult = responseCode;
            if(!responseCode.equals(Integer.valueOf(200))){
                throw new BadResponseException("活体检测未通过");
            }
            checkMessage = MapUtil.getStr(authResponseMap, "msg");
            String userAuthData = MapUtil.getStr(authResponseMap, "data");
            if(StrUtil.isBlank(userAuthData)) {
                throw new BadResponseException("人脸活体检测异常");
            }
            Map<String, Object> responseDataMap = JSONObject.parseObject(userAuthData, Map.class);
            checkFaceImg = MapUtil.getStr(responseDataMap, "faceImageUrl");
        } catch (Exception e) {
            updateWrapper.set(EbMemberLife::getCheckResult, checkResult);
            updateWrapper.set(EbMemberLife::getCheckMessage, e.getMessage());
            updateWrapper.set(EbMemberLife::getCheckFaceImg, checkFaceImg);
            this.update(updateWrapper);
            throw new BadResponseException(e.getMessage());
        }

        updateWrapper.set(EbMemberLife::getCheckResult, checkResult);
        updateWrapper.set(EbMemberLife::getCheckMessage, checkMessage);
        updateWrapper.set(EbMemberLife::getCheckFaceImg, checkFaceImg);
        this.update(updateWrapper);

        return this.getById(memberLife.getId());
    }

    @Override
    public EbMemberLife getByToken(String token) {
        return this.getOne(new LambdaQueryWrapper<EbMemberLife>()
                .eq(EbMemberLife::getThirdToken, token)
                .last("limit 0,1"));
    }
}
